/**
 * Created by moko1988 on 15/12/1.
 */
define([
    'backbone',
    'models/hotGame/list',
    'text!templets/hotGame/list.html',
    'text!templets/hotGame/list-modal-add-insert.html',
    'utils/dataTableUtil',
    'uploadify',
    'utils/urlUtil',
    'jquerypage',
    'select2',
    'moment'
], function(
    BackBone,
    Model,
    Tpl,
    ModalAddIn,
    DataTable,
    UrlUtil
) {
    var view = Backbone.View.extend({
        el: '#CONTENT',
        events: {
            'click [role=add]': 'addFun', //添加资源
            'click [role=edit]': 'editFun', //修改资源
            'click [role=del]': 'delFun', //删除资源
            'click [role=close]': 'closeFun', //关闭
            'click [role=saveAdd]': 'saveAdd',    //保存添加
            'change #pageSize': 'changePageSize', //选择分页宽度
            'click [role=rank]': 'rank', //排序
            'click [role=review]': 'review', //审核
             'click [role=saveChange]': 'saveChange',//保存修改 
            'click [role=recommend]': 'recommend', //推荐
            'click #checkAll': 'checkAll', //全选、取消
            'click input[name=idarr]': 'checkItem' //选择、取消单条记录
       
        },
        /*初始化*/
        initialize: function() {
            $(this.el).html(Tpl);
            $(this.el).off();
            this.page = '1';
            this.listRows = '10';
            this.idArr = [];
            this.categoryid = '';
            $('#pageSize').select2();
            this.render();
        } ,
       
        /*排序*/
        rank: function(e) {
            var $target = $(e.currentTarget),
                type = $target.attr('data-type'),
                id = $target.attr('data-id'),
                _this = this;
            Model.rank({
                type: 'post',
                data: {
                    id: id,
                    type: type
                },
                success: function() {
                    jAlert('操作成功！', function() {
                        _this.render();
                    });
                }
            })
        },
        /*全选、取消*/
        checkAll: function(e) {
            var $target = $(e.currentTarget),
                isCheck = $target.prop('checked'),
                _this = this;
            if (isCheck) {
                $('input[name=idarr]').prop('checked', true);
                $('input[name=idarr]').each(function() {
                    _this.idArr.push($(this).val());
                })
            } else {
                $('input[name=idarr]').prop('checked', false);
                this.idArr = [];
            }
        },
        /*选择、取消单条记录*/
        checkItem: function() {
            this.idArr = [];
            var isCheckAll = true,
                _this = this;
            $('input[name=idarr]').each(function() {
                if ($(this).prop('checked')) {
                    _this.idArr.push($(this).val());
                } else {
                    isCheckAll = false;
                }
            })
            if (isCheckAll) {
                $('#checkAll').prop('checked', true);
            } else {
                $('#checkAll').prop('checked', false);
            }
        },
        /*选择分页宽度*/
        changePageSize: function(e) {
            var $target = $(e.currentTarget),
                val = $target.val();
            this.listRows = val;
            this.render();
        },
        /*渲染结果列表*/
        render: function() {
            $('#chart_table_div').html(loading);
            var _this = this;
            Model.fetchList({
                type: 'post',
                data: {
                    page: this.page,
                    page_size: this.listRows,
                },
                success: function(map) {
                    var data = map.list,
                        page = map.page,

                        count = data.length;
                    _this.pageTotal = page.total_page;
                    _.each(data,function(o, i){

                         o.checkbox = '<input type="checkbox" value="'+ o.id +'" name="idarr">';

                         var rank_up = '<button class="btn" role="rank" data-type="1" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-up"></i></button>',
                            rank_down = '<button class="btn" role="rank" data-type="0" data-id="' + o.id+ '"><i class="glyphicon glyphicon-arrow-down"></i></button>';

                        if (i == 0) {

                            rank_up = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-up"></i></button>';
                        }
                        if (i == (count - 1)) {

                            rank_down = '<button class="btn" disabled><i class="glyphicon glyphicon-arrow-down"></i></button>';
                        }

                        o.rank = rank_up + rank_down;

                    })
                    var tableHead = ['<input type="checkbox" id="checkAll">', '序号', '游戏名称','游戏id', '排序'],
                        tableBody = _.zip(
                            _.pluck(data,'checkbox'),
                            _.pluck(data,'id'),
                            _.pluck(data,'game_name'),
                            _.pluck(data,'game_id'),
                            _.pluck(data,'rank')

                        );
                    DataTable.drawTable({
                        '$el': $('#chart_table_div'),
                        'thead': tableHead,
                        'tbody': tableBody
                    });
                    $("#pager").pager({
                        pagenumber: _this.page,
                        pagecount: _this.pageTotal,
                        buttonClickCallback: function(page){
                            _this.pageClick(page);
                        }
                    });
                }
            })
        },
        /*分页*/
        pageClick: function(page) {
            var _this = this;
            this.page = page;
            $("#pager").pager({
                pagenumber: this.page,
                pagecount: this.pageTotal,
                buttonClickCallback: function(page){
                    _this.pageClick(page);
                }
            });
            this.render();
        },
       //添加
        addFun: function() {
            $(this.el).append(ModalAddIn);
            var $myModal = $('#myModal');
            $myModal.find('h4').html('添加游戏');
            $myModal.off();
            $myModal.modal();
            $myModal.on('hidden.bs.modal', function(e) {
                $myModal.remove();
            });
             _this = this; 

             Model.fetchGame({
                type: 'post',
                success: function(map) {
                    var opts = '<option value="">游戏名称</option>',
                        category = {};
                    _.each(map, function(o){
                        category[o.id] = o;
                        opts += '<option value="'+o.id+'">'+ o.game_name+'</option>';
                    });
                    _this.categoryOpts = opts;
                    _this.categoryObj = category;
                    $('#game').html(opts).prop('disabled',false).select2();
                    $('[role=saveAdd]').prop('disabled',false);
                    _this.render();
                }
            });
        },
        //添加提交
         saveAdd: function() {
            var _this = this,
                $myModal = $('#myModal'),
                $form = $myModal.find('form[role=form]'),
                subBtn = $myModal.find('button[role=saveAdd]'),
                gameId;

                 //获取下拉框的值      
                gameId = $('#game option:selected').val();

                isOK = this.checkForm();
               
                    Model.insert({
                     type: 'post',
                     data: {
                        game_id: gameId
                     },  
                     success: function() {
                         subBtn.html('提 交').prop('disabled', false);
                            jAlert('提交成功', function() {
                                 $myModal.modal('hide');
                                _this.render();
                             })
                        }                
                  })
        },

       
        /*删除*/
        delFun: function(e) {
            var $target = $(e.currentTarget),
                id = $target.parents('tr').attr('data-id'),
                _this = this;
            if (this.idArr.length) {
                var id = this.idArr.join(',');
                jConfirm('确定要删除？', function(s) {
                    if (s) {
                        Model.delete({
                            type: 'post',
                            data: {
                                id: id
                            },
                            success: function(map) {
                                jAlert('删除成功', function() {
                                    _this.idArr = [];
                                    _this.render();
                                })
                            }
                        })
                    }
                })
            } else {
                jAlert('请选择要操作的数据');
            }

        },

        
         checkForm: function() {
            var $form = $('[role=form]'),
                $number = $form.find('input[name=number]'),
                $phone = $form.find('input[name=phone]'),
                $corp = $form.find('input[name=corp]'),
                $content = $form.find('input[name=content]'),

                getTip = function(e) {
                    var text = e.siblings('label.control-label').html();
                    return text;
                },
                errShow = function(e, msg) {
                    var $err = e.siblings('em');
                    $err.html(msg).css("opacity", '1');
                    $err.stop(0, 0).animate({
                        "opacity": 0
                    }, 3500);
                    rest = false;
                },
                rest = true;
            if ($.trim($number.val()) == '') {
                errShow($number, '请填写' + getTip($number));
            } else if ($number.val().length < 2 || $number.val().length > 20) {
                errShow($number, '请填写2-20个字符');
            }


            if ($.trim($phone.val()) > 100 || $.trim($phone.val()) < 1) {
                errShow($phone, '请填写0~100之间的数字');
            } else  {
                var reg = /^[0-9]*$/;
                 var result = reg.test($phone.val());
                if(!result){
                    errShow($phone, '请填写阿拉伯数字');
                 }
            }

             if ($.trim($corp.val()) == '') {
                errShow($corp, '请填写' + getTip($corp));
            } else {
                 var reg = /^[^\u4e00-\u9fa5]{0,}$/;
                 var result = reg.test($corp.val());
                if(!result){
                    errShow($corp, '请填写正确的格式');
                 }
            }            
            return rest;
        },
    })
    return view;
})

